package com.treeHole.treeHoleServer.fliter;

import ch.qos.logback.core.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.treeHole.treeHoleServer.pojo.Result;
import com.treeHole.treeHoleServer.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;


@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    private static final String[] loginPaths = {
            "/verify",
            "/register",
            "/modifyPassword",
            "/loginByPassword",
            "/loginByVerify"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的url
        String requestURI = request.getRequestURI();
        log.info("requestURI: {}", requestURI);

        for(String loginPath : loginPaths){
            if(requestURI.contains(loginPath)){
                filterChain.doFilter(request, response);//放行不需要登录的请求路径
                return;
            }
        }

        String token = request.getHeader("token");
        log.info("从请求中获得token: {}", token);

        if(!StringUtils.hasLength(token)){
            log.info("token不存在");
            Result result = Result.error("not login!");
            String json= JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");

            response.getWriter().write(json);
            return;
        }

        try{
            JwtUtils.parseJwt(token);
        }catch(Exception e){
            log.info("令牌解析失败!");
            Result result=Result.error("not login!");
            String json= JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");

            response.getWriter().write(json);
            return;
        }
        filterChain.doFilter(request, response);
        return;
    }
    @Override
    public void destroy() {

    }
}
